import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/Users.vue'
import Rights from '../components/Rights.vue'
import Roles from '../components/Roles.vue'
import axios from 'axios'
Vue.use(VueRouter)
// 下面这种引用方式会报错 Uncaught (in promise) TypeError: Cannot read property 'protocol' of undefined
// 正确的引入方式为prototype
// Vue.use(axios)

// 配置请求根路径,这里注意baseURL，否则无法识别根路径
axios.defaults.baseURL = 'http://127.0.0.1:8888/api/private/v1/'
// 配置请求拦截器,网页在请求前首先判断用户是否已经登录
axios.interceptors.request.use(config => {
  config.headers.Authorization = window.sessionStorage.getItem('token')
  // console.log('request拦截器', config)
  return config
}, error => {
  console.log(error)
  return Promise.reject(error)
})
axios.interceptors.response.use(res => {
  // 直接将服务器返回中data提取出来,免得每次都要 .data
  // console.log('response拦截器', res)
  const apiRes = res.data
  return apiRes
}, async error => {
  console.dir(error)
  return Promise.reject(error)
})
Vue.prototype.$http = axios

const routes = [{
  path: '/',
  redirect: '/login'
}, {
  path: '/login',
  component: Login
}, {
  path: '/home',
  redirect: '/welcome',
  component: Home,
  children: [{
    path: '/welcome',
    component: Welcome
  }, {
    path: '/users',
    component: Users
  }, {
    path: '/rights',
    component: Rights
  }, {
    path: '/roles',
    component: Roles
  }]
}]

const router = new VueRouter({
  routes
})

// 路由导航守卫
// to 将要访问的网址
// from 从按个路径跳转而来
// next() 函数，表示放行
router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  const token = window.sessionStorage.getItem('token')
  if (!token) return next('/login')
  next()
})

export default router
